package com.example.demo.controller;

import cn.hutool.core.util.StrUtil;
import com.example.demo.ExcelApplication;
import com.example.demo.cbhs.CalculateConfig;
import com.example.demo.cbhs.ChengBenHeSuanReader;
import com.example.demo.model.ConfigBO;
import com.example.demo.service.AreaPrice;
import com.example.demo.service.AreaWarehouseSell;
import com.example.demo.service.DeliveryPriceConfig;
import com.example.demo.service.WarehouseArea;
import com.example.demo.utils.*;
import com.example.demo.yjcx.BasePriceTypeEnum;
import com.example.demo.yjcx.model.BasePriceBO;
import com.example.demo.yjcx.model.YJCalculateResult;
import com.example.demo.yjcx.service.BasePriceService;
import com.example.demo.yjcx.service.YJCalculateService;
import com.example.demo.zb.ExcelReader;
import javafx.beans.property.ReadOnlyStringWrapper;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.collections.transformation.FilteredList;
import javafx.collections.transformation.SortedList;
import javafx.event.ActionEvent;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.geometry.Insets;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.control.Button;
import javafx.scene.control.Dialog;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyEvent;
import javafx.scene.layout.*;
import javafx.scene.paint.Color;
import javafx.scene.text.Text;
import javafx.scene.web.WebEngine;
import javafx.scene.web.WebView;
import javafx.stage.FileChooser;
import javafx.stage.Modality;
import javafx.stage.Stage;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class IndexController {

    File uploadedFile; // 保存上传文件的引用

    @FXML
    private Button fileBtn;

    @FXML
    private Button cbhsBtn;

    @FXML
    private Button configBtn;

    @Autowired
    private PriceSearchController priceSearchController;

    @FXML
    private Button yjConfigBtn;

    @FXML
    private Button freightQueryBtn;

    @FXML
    private Button makeYbBtn;

    @FXML
    private Button qdConfigBtn;

    @FXML
    private Button customerBtn;

    @Autowired
    private YJCalculateService yjCalculateService;

    @Autowired
    private ZbController zbController;



    @FXML
    void qdConfig(ActionEvent event) {
        zbController.showConfigView();
    }

    @FXML
    void customerView(ActionEvent event) throws URISyntaxException {
        // 创建WebView并加载网页
        //WebView webView = new WebView();
        //WebEngine webEngine = webView.getEngine();
        //webEngine.load("http://localhost:8099/customer/page?customer=");
        //
        //// 请替换为你想加载的网页URL
        ////webEngine.load("https://www.baidu.com/"); // 请替换为你想加载的网页URL
        //// 将WebView嵌入到对话框的内容中
        //BorderPane pane = new BorderPane();
        //pane.setCenter(webView);
        //
        //Stage dialogStage = new Stage();
        //dialogStage.initModality(Modality.WINDOW_MODAL);
        //dialogStage.initOwner(StageUtils.stage);
        //dialogStage.setTitle("客户");
        //
        //Scene scene = new Scene(pane);
        //dialogStage.setScene(scene);
        //dialogStage.setWidth(1200);
        //dialogStage.setHeight(600);
        //dialogStage.show();


    }

    @FXML
    void makeYb(ActionEvent event) {

        // 设置场景和舞台
        Stage dialogStage = new Stage();
        //dialogStage.initModality(Modality.WINDOW_MODAL);
        dialogStage.initOwner(StageUtils.stage);

        // 设置为模态窗口
        dialogStage.initModality(Modality.APPLICATION_MODAL);
        dialogStage.setTitle("请输入要筛选的渠道用,分割");

        // 创建输入框和按钮
        TextField inputField = new TextField();
        Button confirmButton = new Button("确定");

        // 确定按钮的点击事件
        confirmButton.setOnAction(e -> {
            String qd = inputField.getText();
            FileChooser fileChooser = new FileChooser();
            //定义文件后缀名过滤器
            FileChooser.ExtensionFilter filter =
                    new FileChooser.ExtensionFilter("file", new String[]{"*.xlsx"});
            //为文件选择器添加下拉框
            fileChooser.getExtensionFilters().add(filter);
            File file = fileChooser.showOpenDialog(StageUtils.stage);
            if (file == null) {
                return;
            }
            try {
                ExcelReader.yuebao(file, qd);
            } catch (Exception ex) {
                ex.printStackTrace();
                showAlert("解析失败");
            }
            dialogStage.close(); // 关闭输入框
        });

        // 布局
        VBox dialogLayout = new VBox(10);
        dialogLayout.getChildren().addAll(inputField, confirmButton);

        Scene dialogScene = new Scene(dialogLayout, 250, 150);
        dialogStage.setScene(dialogScene);

        dialogStage.show();

    }



    @FXML
    void viewSearchPage(ActionEvent event) {
        priceSearchController.showPriceSearchView();
    }

    @FXML
    void configYj(ActionEvent event) {
        priceSearchController.showConfigView();
    }

    @FXML
    void viewConfig(ActionEvent event) {
        createConfigView(StageUtils.stage);
    }

    private void createConfigView(Stage ownerStage) {
        // 创建 TabPane
        TabPane tabPane = new TabPane();

        // 假设我们需要创建三个带表格的标签页
        Map<String, AreaWarehouseSell> areaWarehouseSellMap = DeliveryPriceConfig.getAreaWarehouseSellMap();
        for (Map.Entry<String, AreaWarehouseSell> e : areaWarehouseSellMap.entrySet()) {
            String key = e.getKey();
            // 创建 Tab
            Tab tab = new Tab(key);
            tab.setClosable(false);
            // 创建 TableView 并设置到 Tab
            VBox tableView = createTableView(key, e.getValue());
            tab.setContent(tableView);

            // 将 Tab 添加到 TabPane 中
            tabPane.getTabs().add(tab);
        }


        // 创建一个 VBox 作为根节点，并将 TabPane 添加到其中
        VBox root = new VBox(tabPane);

        Stage dialogStage = new Stage();
        dialogStage.initModality(Modality.WINDOW_MODAL);
        dialogStage.initOwner(ownerStage);
        dialogStage.setTitle("价格配置信息");

        // 设置场景和舞台
        Scene scene = new Scene(root);
        dialogStage.setScene(scene);
        dialogStage.setWidth(400);
        dialogStage.show();

    }

    private String temp = "[{}-{}]=${}";
    private String FULL_CAR_TEMP = "${}/{}";

    // 创建 TableView 的方法
    private VBox createTableView(String tabName, AreaWarehouseSell sellData) {
        // 创建 TableView
        TableView<ConfigBO> tableView = new TableView<>();

        // 创建第一列，并与Person类firstName属性绑定
        TableColumn<ConfigBO, String> wCol = new TableColumn<>("仓库");
        wCol.setCellValueFactory(cellData -> cellData.getValue().warehouse());

        // 创建第二列，并与Person类lastName属性绑定
        TableColumn<ConfigBO, String> areaCol = new TableColumn<>("区间");
        areaCol.setCellValueFactory(cellData -> cellData.getValue().priceArea());

        TableColumn<ConfigBO, String> fullCarCol = new TableColumn<>("整车价");
        fullCarCol.setCellValueFactory(cellData -> cellData.getValue().fullCarPrice());
        // 将列添加到TableView
        tableView.getColumns().addAll(wCol, areaCol,fullCarCol);

        ObservableList<ConfigBO> data = FXCollections.observableArrayList();

        Integer boardOfCar = sellData.getBoardOfCar();
        List<WarehouseArea> warehouseAreaList = sellData.getWarehouseAreaList();

        for (WarehouseArea warehouseArea : warehouseAreaList) {
            // 整车价
            BigDecimal fullPrice = warehouseArea.getFullPrice();
            // 仓库名
            String warehouse = warehouseArea.getWarehouse();

            List<AreaPrice> areaPriceList = warehouseArea.getAreaPriceList();
            String priceArea = areaPriceList.stream().map(s -> {
                Integer max1 = s.getMax();
                String max = Integer.MAX_VALUE == max1 ? "∞" : max1.toString();
                return StrUtil.format(temp, s.getMin(), max, BigDecimalUtils.toPlainString(s.getAmount()));
            }).collect(Collectors.joining("\r\n"));

            String fullCarInfo;
            if (fullPrice == null || BigDecimalUtils.equals(fullPrice, new BigDecimal(Integer.MAX_VALUE))) {
                fullCarInfo = "无";
            } else {
                fullCarInfo = StrUtil.format(FULL_CAR_TEMP, BigDecimalUtils.toPlainString(fullPrice), boardOfCar);
            }

            ConfigBO configBO = new ConfigBO();
            configBO.setWarehouse(warehouse);
            configBO.setPriceArea(priceArea);
            configBO.setFullCarPrice(fullCarInfo);
            data.add(configBO);
        }

        // 创建一个FilteredList包装原来的ObservableList
        FilteredList<ConfigBO> filteredData = new FilteredList<>(data, p -> true);

        // 创建一个输入框用于输入查询条件
        TextField textField = new TextField();
        textField.setPromptText("请输入仓库");
        textField.textProperty().addListener((observable, oldValue, newValue) -> {
            filteredData.setPredicate(c -> {
                // 如果过滤文本为空，显示所有人
                if (newValue == null || newValue.isEmpty()) {
                    return true;
                }

                // 将查询条件转换为小写
                String lowerCaseFilter = newValue.toLowerCase();

                // 如果Person的名字或姓氏匹配查询条件，则返回true
                return c.getWarehouse().toLowerCase().contains(lowerCaseFilter);
            });
        });

        // 将过滤后的数据包装到一个SortedList
        SortedList<ConfigBO> sortedData = new SortedList<>(filteredData);
        sortedData.comparatorProperty().bind(tableView.comparatorProperty());

        // 设置数据到表格
        tableView.setItems(sortedData);
        VBox vbox = new VBox(textField, tableView);
        return vbox;
    }

    @FXML
    void doCbhs(ActionEvent event) {
        createDialog(StageUtils.stage);
    }

    private void createDialog(Stage ownerStage) {
        // 新的Stage作为弹窗
        Stage dialogStage = new Stage();
        dialogStage.initModality(Modality.WINDOW_MODAL);
        dialogStage.initOwner(ownerStage);
        dialogStage.setTitle("核算信息");

        ComboBox<String> comboBox = new ComboBox<>();

        // 向ComboBox添加选项
        comboBox.getItems().addAll(
                DeliveryPriceConfig.getDeliveryPriceArea()
        );
        String defaultArea = "纽约";
        comboBox.getSelectionModel().select(defaultArea);

        // 输入框1及其标签
        Label label1 = new Label("海运费:");
        TextField inputField1 = createDecimalTextField();


        // 输入框2及其标签
        Label label2 = new Label("包税头程:");
        TextField inputField2 = createDecimalTextField();


        // 输入框3及其标签
        Label label3 = new Label("不包税头程:");
        TextField inputField3 = createDecimalTextField();

        resetPrice(defaultArea, inputField1, inputField2, inputField3);

        // 添加监听器以便在选项变化时触发
        comboBox.valueProperty().addListener((observable, oldValue, newValue) -> {
            System.out.println("选中的选项: " + newValue);
            if (!StringUtils.equals(oldValue, newValue)) {
                resetPrice(newValue, inputField1, inputField2, inputField3);
            }
        });
        // 文件上传按钮
        Button uploadButton = new Button("选择核算文件");

        Text txtFileName = new Text();

        uploadButton.setOnAction(uploadEvent -> {
            FileChooser fileChooser = new FileChooser();
            fileChooser.setTitle("Select File");
            uploadedFile = fileChooser.showOpenDialog(dialogStage);
            if (uploadedFile != null) {
                txtFileName.setText(uploadedFile.getName());
                System.out.println("File selected: " + uploadedFile.getAbsolutePath());
            }
        });

        // 提交按钮
        Button submitButton = new Button("开始核算");
        submitButton.setOnAction(submitEvent -> {
            // 提交逻辑
            String text1 = inputField1.getText();
            String text2 = inputField2.getText();
            String text3 = inputField3.getText();

            String area = comboBox.getSelectionModel().getSelectedItem();
            if (StringUtils.isBlank(text1) ||
                    StringUtils.isBlank(text3) ||
                    StringUtils.isBlank(text2) || StringUtils.isBlank(area)) {
                showAlert("请填写费用");
                return;
            }
            if (uploadedFile == null) {
                showAlert("请上传文件");
                return;
            }
            CalculateConfig calculateConfig = new CalculateConfig();
            calculateConfig.setBsHeadPrice(new BigDecimal(text2));
            calculateConfig.setUnBsHeadPrice(new BigDecimal(text3));
            calculateConfig.setHyfBasePrice(new BigDecimal(text1));
            calculateConfig.setFile(uploadedFile);
            calculateConfig.setArea(area);
            try {
                ChengBenHeSuanReader.doCbhs(calculateConfig);
                dialogStage.close(); // 关闭对话框
            } catch (Exception e) {
                e.printStackTrace();
                showAlert(e.getMessage());
            }

        });

        // 布局设置
        GridPane gridPane = new GridPane();
        gridPane.setVgap(10);
        gridPane.setHgap(10);
        gridPane.setPadding(new Insets(20));
        VBox vBox = new VBox(uploadButton, txtFileName);

        // 添加到GridPane布局
        gridPane.add(label1, 0, 0);
        gridPane.add(inputField1, 1, 0);
        gridPane.add(label2, 0, 1);
        gridPane.add(inputField2, 1, 1);
        gridPane.add(label3, 0, 2);
        gridPane.add(inputField3, 1, 2);
        gridPane.add(comboBox, 0, 3, 2, 1);
        gridPane.add(vBox, 0, 4, 2, 1);
        gridPane.add(submitButton, 0, 5, 2, 1);

        // 设置场景和显示
        Scene dialogScene = new Scene(gridPane);
        dialogStage.setScene(dialogScene);
        dialogStage.show();
    }

    private void resetPrice(String defaultArea, TextField inputField1, TextField inputField2, TextField inputField3) {
        YJCalculateResult yjCalculateResult = yjCalculateService.calculateByArea(DeliveryPriceConfig.getName(defaultArea));
        if (yjCalculateResult != null) {
            inputField1.setText(BigDecimalUtils.toPlainString(yjCalculateResult.getHyf()));
            inputField2.setText(BigDecimalUtils.toPlainString(yjCalculateResult.getWeightPrice()));
            inputField3.setText(BigDecimalUtils.toPlainString(yjCalculateResult.getVolumePrice()));
        } else {
            inputField1.setText("");
            inputField2.setText("");
            inputField3.setText("");
        }
    }

    private void showAlert(String msg) {
        AlertUtils.showAlert(msg);
    }


    private TextField createDecimalTextField() {
        return TextFieldUtils.createDecimalTextField();
    }


    @FXML
    void importFile(ActionEvent event) {
        FileChooser fileChooser = new FileChooser();
        //定义文件后缀名过滤器
        FileChooser.ExtensionFilter filter =
                new FileChooser.ExtensionFilter("file", new String[]{"*.xlsx"});
            //为文件选择器添加下拉框
        fileChooser.getExtensionFilters().add(filter);
        File file = fileChooser.showOpenDialog(StageUtils.stage);
        if (file == null) {
            return;
        }
        try {
            ExcelReader.newkWeelyReport(file);
        } catch (Exception e) {
            e.printStackTrace();
            showAlert("解析失败");
        }
    }

}
